<template >
  <div class="JNPF-common-layout-local" v-if="showPage">
    <div style="width:100%;height: 100%;">
      <div class="JNPF-common-page-header">
        <div v-if="formConfig.showTitle && formConfig.label">
          <h2 >{{ formConfig.label }}</h2>
        </div>
        <!-- <div class="options">
          <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">
            {{formConf.confirmButtonText||'确 定'}}</el-button>
          <el-button type="warning" @click="resetForm()">重置</el-button>
        </div> -->
      </div>
      <div class="dynamic-form-main" :style="{margin: '0 auto',width:formConf.fullScreenWidth}">
        <parser :form-conf="formConf" @submit-inner="submitForm" :relationInfo="relationInfo" :key="key" ref="dynamicForm"
          v-if="!loading" />
      </div>
    </div>
  </div>
  <div v-else>
        <p class="JNPF-Text">子表无数据</p>
  </div>
</template>


<script>

import { createModel } from '@/api/onlineDev/visualDev'
import Parser from '@/components/Generator/parser/Parser'

export default {
  components: { Parser },
  props: {
    config: {
      type: Object,
      default: () => { 
      }
    },
    modelId: {
      type: String,
      default: ''
    },
    formConfig: {
      type: Object,
      default: () => { 
      }
    },
    isDetail:{
        type: Boolean,
        default: false
    },
   
   relationInfo: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      showPage:false,
      visible: false,
      dataForm: {
        data: ''
      },
      btnLoading: false,
      loading: true,
      key: +new Date(),
      formConf: {},
      foreignFieldItem:{},
      initData:{},
      fieldMap:this.config.fieldMap,
      subFieldMap:{},// by jdeng 子表与主表的字段映射扁平化
    }
  },
  created() {
    // debugger
    let {foreignField,foreignId} = this.relationInfo
    this.formData = JSON.parse(this.config.formData)
    let {fields} = this.formData
    /**
     * 子表form中必须加外键字段
     */
    let exitForeignField = false
    const loop = list => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if(item.__vModel__&&item.__vModel__.toLowerCase() === foreignField.toLowerCase()){
            exitForeignField = true
            this.foreignFieldItem = item
            return
          }
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
    foreignField && loop(fields)
    if(!exitForeignField){
      this.showPage = false
      return
    }
    this.showPage = true
    this.init()

    // this.setValue(foreignField,foreignId)

   
  },
  mounted(){
    // debugger
    // this.$refs.dynamicForm && this.$refs.dynamicForm.setValue2(this.foreignFieldItem['__config__'],foreignField,foreignId)
  },
  methods: {
    init() {
      this.formConf = JSON.parse(this.config.formData)
      this.initData = this.formConfig.initData
      this.loading = true
      this.formatSubFieldMap()
      this.$nextTick(() => {
        this.visible = true
        this.loading = false
        this.key = +new Date()
        this.fillFormData(this.formConf,this.initData)

      })
    },
    /**
     * by jdeng 子表与主表的字段映射扁平化
     */
     formatSubFieldMap(){
      // debugger
      if(this.relationInfo&&this.relationInfo.fieldMap){
        let map = {}
        this.relationInfo.fieldMap.forEach((o)=>{
          if(o.tableField&&o.relationField){
            map[o.tableField] = o.relationField
          }
        })
        this.subFieldMap = map
      }
    },
    fillFormData(form, data) {
      // debugger
      // by jdeng
      this.initDynamicConfig(form.fields,data)
      // end by jdeng
      const loop = list => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            let val = data?data[item.__vModel__]:null
            if(this.relationInfo&&this.subFieldMap){
                //  debugger
                 let mainField = this.subFieldMap[item.__vModel__]
                 if(mainField){
                  let mainTableDynamicModelExtra = this.$store.state.generator.mainTableDynamicModelExtra
                  if(mainTableDynamicModelExtra){
                    let mainValue = mainTableDynamicModelExtra[mainField]
                    if(mainValue !== undefined){
                      val = mainValue
                    }
                  }
                 }
               }
            if (val !== undefined && val != null) {
              item.__config__.defaultValue = val
            }
            if (!this.isPreview && this.useFormPermission) {
              let noShow = true
              if (this.formOperates && this.formOperates.length) {
                noShow = !this.formOperates.some(o => o.enCode === item.__vModel__)
              }
              noShow = item.__config__.noShow ? item.__config__.noShow : noShow
              this.$set(item.__config__, 'noShow', noShow)
            }
          }
          /**
           * by jdeng 设置defaultValue
           */
          if (item.__config__ && (
            item.__config__.jnpfKey === 'listTable'
            ||item.__config__.jnpfKey === 'flowstagelog'
          )){
            this.existSubTableList = true
            // 在src/components/Generator/parser/Parser.vue中会将__config__.defaultValue赋值给foreignId属性
            item.__config__.defaultValue = this.dataForm.id?this.dataForm.id:this.clientUUID

            let __subTableDatas__ = data?data['__subTableDatas__']:null
            if(__subTableDatas__){
              let subData = __subTableDatas__[item.__config__.tableName]
              item.__config__.initData = subData
            }
    
          }
          // end by jdeng
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.jnpfKey !== 'listTable' && item.__config__.jnpfKey !== 'flowstagelog' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
      loop(form.fields)
      this.fillForeignId(form.fields,data)
    },
    fillForeignId(componentList,formData){
      // debugger
      if(!this.relationInfo){
        return
      }
      let {foreignField,foreignId} = this.relationInfo
      if(foreignField&&foreignId){
        componentList.forEach(cur => {
          if (cur.__vModel__ === foreignField) {
            cur.__config__.defaultValue = foreignId
            return;
          }
        })
      }
    },
    /**
     * by jdeng 解析动态配置
     * @param {*} componentList 
     */
     initDynamicConfig(componentList,formData){
      // debugger
      let dynamicItem
      componentList.forEach(cur => {
        if (cur.__vModel__ === 'F_FormDynamicConf') {
          dynamicItem = cur
          return;
        }
      })
      if(!dynamicItem){
        return;
      }
      const config = dynamicItem.__config__
      const vModel = dynamicItem.__vModel__
      const initConfigCall = (list,key,prop,value)=>{
        list.forEach(cur => {
          const config = cur.__config__
          if (cur.__vModel__ === key) {
            config[prop]=value
            return
          }
          if (cur.__config__.jnpfKey == 'table') return
          if (config.children) initConfigCall(config.children, key,prop,value)
        })
      }
      try{
          let dynamicJsonStr = formData?formData[vModel]:null
          if(dynamicJsonStr){
            config.defaultValue = dynamicJsonStr
            let dynamicJson = JSON.parse(dynamicJsonStr)
            if(dynamicJson){
              if(dynamicJson.showOrHide){ // 动态设置显示隐藏属性
                let showOrHide = dynamicJson.showOrHide
                for (let key in showOrHide) {
                  const newVal = !!showOrHide[key]
                  initConfigCall(componentList,key,'noShow',!newVal)
                }
              }
              if(dynamicJson.currency){ // 动态设置显示隐藏属性
                let currency = dynamicJson.currency
                for (let key in currency) {
                  const newVal = currency[key]
                  initConfigCall(componentList,key,'currency',newVal)
                }
              }
              if(dynamicJson.flowStag){ // 动态设置流程步骤属性
                
              }
            }
           
          }
      }catch(e){
        console.error(e)
      }
    },
   
    submitForm(data, callback) {
      debugger
      if (!data) return
      this.btnLoading = true
      this.dataForm.data = JSON.stringify(data)
      createModel(this.modelId, this.dataForm).then(res => {
        this.$message({
          message: res.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            if (callback && typeof callback === "function") callback(res.data)
            this.btnLoading = false
            // this.resetForm()
          }
        })
      }).catch(() => { this.btnLoading = false })
    },
    dataFormSubmit() {
      debugger
      this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm()
    },
    resetForm() {
      this.formConf = JSON.parse(this.config.formData)
      this.$nextTick(() => {
        let {foreignField,foreignId} = this.relationInfo
        this.$refs.dynamicForm && this.$refs.dynamicForm.resetForm()
        this.$refs.dynamicForm && this.$refs.dynamicForm.setFormData(foreignField,foreignId)
      })
    }
  }
}
</script>

<style lang="scss">
.JNPF-common-layout-local {
  height: 100%;
  width: 100%;
  display: flex;
  position: relative;

  .JNPF-common-layout-left {
    width: 220px;
    background-color: #fff;
    flex-shrink: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-right: 10px;

    .JNPF-common-title {
      flex-shrink: 0;
      padding: 0 10px;
    }

    .JNPF-common-tree-search-box {
      padding: 10px 10px 0;
    }

    .JNPF-common-el-tree-scrollbar {
      flex: 1;

      .el-scrollbar__wrap {
        overflow-x: hidden;
      }
    }

    .custom-tree-node {
      width: calc(100% - 30px) !important;
    }

    .JNPF-common-el-tree {
      flex: 1;
      overflow: auto;
      overflow-x: hidden;

      .el-tree-node__content {
        height: 40px;
        line-height: 40px;
      }

      // .is-current>.el-tree-node__content .custom-tree-node {
      //   color: #409eff;
      // }
    }
  }
}
</style>
